class TopicsController < ApplicationController
  before_filter :setup
  before_filter :login_required , :except => [:index,:show] 
  layout :set_layout
  
  def index
    redirect_to forum_path
  end

  def new
    @post = @topic.posts.build
    
  end
  
  def show
    
  end

  def edit
  end
  
  def create
    
    @topic = @forum.topics.find :first
    respond_to do |wants|
      wants.html {   }
      wants.js do
        render :update do |page|
          # page<<"alert('hi11')"
          page<<"tb_remove()"
          page.insert_html :after, "topic_labels_row", :partial => 'topic'
          # page.insert_html :after, "topic_labels_row", :partial => "topic",:locals => {:topic  => @topic}
          
        end
      end
    end
  end
  
  
  
  def create1
    # raise
    @topic = @forum.topics.build(params[:topic])
    @topic.user = current_user
    
    begin
      Topic.transaction do
        Post.transaction do
        b1=@topic.save
        @post = @topic.posts.build(params[:post])
        @post.user = current_user
        b2=@post.save
        end
      end
      return
    rescue Exception => e
      raise e
    end
        
    post_response b1&&b2
    
  end

  private
  
  def setup
    @forum = Forum.find( params[:forum_id])
    #build a topic belongs to this forum
    @topic = params[:id] ? Topic.find( params[:id]) : @forum.topics.build
  end
  
  
  def set_layout
    if request.xhr?
      false
    else
       "application"
    end
  end
  
  def post_response saved
    respond_to do |format|
      if saved
        format.html do 
          flash[:notice] = '帖子保存成功！'
          redirect_to(action_name == 'create' ? forum_topic_url(@forum, @topic) : (forum_path(@topic.forum))) 
        end
        
        format.xml  { render :xml => @topic}
        
        format.js do
          render :update do |page|
            if @controller.action_name == 'create'
              page.insert_html :after, "topic_labels_row", :partial => 'topics/topic', :object => @topic
              page.visual_effect :fade, "no_topics_message"
              page.alert "new topics 谢谢"
              # page.replace_html "forum_details", forum_details(@forum)
            else
              page.replace @topic.dom_id, :partial => 'forum_topics/topic', :object => @topic
              page << "$('TB_ajaxContent').innerHTML = ''" #otherwise we get double content on next show
            end
            page << "tb_init('\##{@topic.dom_id}_edit_link')"
            page << "tb_remove()"
            page.visual_effect :highlight, @topic.dom_id
          end
        end
        
      else
        format.html { render :action => (action_name == 'create' ? "new" : "edit") }
        
        format.xml  { render :xml => @topic.errors, :status => :unprocessable_entity }
        
        format.js do
          render :update do |page|
            page.alert @topic.errors.to_s
          end
        end
        
      end
    end
  end
  
end
